CC := $(CC)
AARCH64_CC := $(shell command -v aarch64-linux-gnu-gcc 2>/dev/null)
# If CC is the default built-in 'cc', prefer aarch64 cross gcc when available
ifeq ($(origin CC), default)
  ifneq ($(AARCH64_CC),)
    CC := $(AARCH64_CC)
  endif
endif

CFLAGS ?= -O2 -fPIC -Wall -Wextra
LDFLAGS ?= -shared -ldl
BUILD_DIR ?= build
OUT := $(BUILD_DIR)/libsample_dlsym.so
OUT_OPT := $(BUILD_DIR)/libopt_dlsym.so
OUT_MULTI := $(BUILD_DIR)/libmulti_calls.so

SRC := sample_dlsym.c
SRC_OPT := opt_sample.c
SRC_MULTI := multi_calls.c

.PHONY: all clean

all: $(OUT) $(OUT_OPT) $(OUT_MULTI)

$(BUILD_DIR):
	@mkdir -p $@

$(OUT): $(SRC) | $(BUILD_DIR)
	@echo "[CC] $(CC) $< -> $@"
	$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS)
	@file $@ | grep -qi "aarch64\|arm64" || (echo "Error: built object is not AArch64. Use 'make CC=aarch64-linux-gnu-gcc' or install cross toolchain." && false)

$(OUT_OPT): $(SRC_OPT) | $(BUILD_DIR)
	@echo "[CC][OPT] $(CC) $< -> $@ (LTO)"
	$(CC) $(CFLAGS) -flto -o $@ $< $(LDFLAGS) -flto
	@file $@ | grep -qi "aarch64\|arm64" || (echo "Error: built object is not AArch64. Use 'make CC=aarch64-linux-gnu-gcc' or install cross toolchain." && false)

$(OUT_MULTI): $(SRC_MULTI) | $(BUILD_DIR)
	@echo "[CC][MULTI] $(CC) $< -> $@"
	$(CC) $(CFLAGS) -o $@ $< $(LDFLAGS)
	@file $@ | grep -qi "aarch64\|arm64" || (echo "Error: built object is not AArch64. Use 'make CC=aarch64-linux-gnu-gcc' or install cross toolchain." && false)

clean:
	rm -rf $(BUILD_DIR)
